package java.designPattern.creational;

/**
 * 单例模式
 */
public class Singleton {
}

/**
 * 饿汉式单例模式
 */
class EagerSingletonBasic {
    // 类加载时就创建实例
    private static final EagerSingletonBasic instance = new EagerSingletonBasic();
    // 私有构造函数
    private EagerSingletonBasic() {
        // 防止反射创建实例
        if (instance != null) {
            throw new RuntimeException("单例模式禁止反射创建");
        }
    }
    // 全局访问点
    public static EagerSingletonBasic getInstance() {
        return instance;
    }

}

/**
 * 饿汉式单例模式：静态
 */
class EagerSingletonStatic {
    private static final EagerSingletonStatic instance;
    // 静态代码块初始化
    static {
        instance = new EagerSingletonStatic();
    }
    private EagerSingletonStatic() {}
    public static EagerSingletonStatic getInstance() {
        return instance;
    }
}

/**
 * 懒汉式单例模式
 * 非线程安全版本
 */
class UnsafeLazySingleton {
    private static UnsafeLazySingleton instance;
    private UnsafeLazySingleton() {}
    public static UnsafeLazySingleton getInstance() {
        if (instance == null) {
            instance = new UnsafeLazySingleton();
        }
        return instance;
    }
}

/**
 * 懒汉式单例模式
 * 线程安全版本
 */
class SynchronizedLazySingleton {
    private static SynchronizedLazySingleton instance;
    private SynchronizedLazySingleton() {}
    // 方法同步，性能较差
    public static synchronized SynchronizedLazySingleton getInstance() {
        if (instance == null) {
            instance = new SynchronizedLazySingleton();
        }
        return instance;
    }
}

/**
 * 懒汉式单例模式
 * 双检查版本
 */
class DoubleCheckedSingleton {
    // 使用 volatile 保证可见性和禁止指令重排序
    private static volatile DoubleCheckedSingleton instance;
    private DoubleCheckedSingleton() {}
    public static DoubleCheckedSingleton getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (DoubleCheckedSingleton.class) {
                if (instance == null) { // 第二次检查
                    instance = new DoubleCheckedSingleton();
                }
            }
        }
        return instance;
    }
}

/**
 * 懒汉式单例模式
 * 静态内部类版本
 */
class StaticInnerClassSingleton {
    private StaticInnerClassSingleton() {
        // 防止反射攻击
        if (SingletonHolder.INSTANCE != null) {
            throw new RuntimeException("不允许创建多个实例");
        }
    }
    // 静态内部类
    private static class SingletonHolder {
        private static final StaticInnerClassSingleton INSTANCE = new StaticInnerClassSingleton();
    }
    public static StaticInnerClassSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

